package com.tiantian.job.jobdemo;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 分配算法演示
 *
 * @author TianTian
 */
public class demo {
    public static void main(String[] args) {
        // 新人集合
        List<SysUser> newcomerList = new ArrayList<>();
        // 判题人集合
        List<SysJudger> judgerList = new ArrayList<>();
        // 模拟数据
        mockData(newcomerList, judgerList);
        // 进行分配
        assignNewcomerToJudger(newcomerList, judgerList);
        System.out.println("50个答题用户和13个判题用户的分配");

        // 输出结果，检查每个管理员分配的用户数量是否接近平均
        for (SysJudger judger : judgerList) {
            System.out.println("判题用户 judgerId: " + judger.getUserId() + " 分配到的答题用户 ids: " + judger.getReplyUsers() + " 数量为: " + judger.getReplyUsers().size());
        }

    }

    /**
     * 50:13 模拟不完全分配
     */
    private static void mockData(List<SysUser> newcomerList, List<SysJudger> judgerList) {
        // 新人数量
        for (int i = 0; i < 50; i++) {
            newcomerList.add(new SysUser((long) i));
        }
        // 判题人数量
        for (int i = 0; i < 13; i++) {
            judgerList.add(new SysJudger((long) i, new ArrayList<>()));
        }
    }


    public static void assignNewcomerToJudger(List<SysUser> newcomerList, List<SysJudger> judgerList) {
        // 打乱顺序
        Collections.shuffle(newcomerList);
        Collections.shuffle(judgerList);
        if (newcomerList.size() > judgerList.size()) {
            for (int i = 0; i < newcomerList.size(); i++) {
                judgerList.get(i % judgerList.size())           // 获取判题人
                        .getReplyUsers()                        // 获取被判新人集合
                        .add(newcomerList.get(i).getUserId());  // 添加新人Id
            }
        } else {
            int newcomerCount = newcomerList.size();
            int judgerCount = judgerList.size();
            // 每个判题人平均分配的新人数
            int newcomerPerJudger = newcomerCount / judgerCount;
            // 多余新人的数量
            int remainingNewcomers = newcomerCount % judgerCount;
            for (int i = 0; i < newcomerPerJudger * judgerCount; i++) {
                judgerList.get(i % judgerList.size())
                        .getReplyUsers()
                        .add(newcomerList.get(i).getUserId());
            }
            for (int i = 0; i < remainingNewcomers; i++) {
                // 将多余的新人分配给前面的判题人
                judgerList.get(i % judgerList.size())
                        .getReplyUsers()
                        .add(newcomerList.get(newcomerPerJudger * judgerCount + i).getUserId());
            }

        }
    }


}
